<template>
  <div>
    <router-view>
      <div class="box" v-if="status">
        <el-card class="box-card">
          <template #header>
            <div style="font-size: 20px; font-weight: 600">
              <span>药品管理</span>
            </div>
            <div style="height: 2vh"></div>
            <div class="header">
              <div class="left">
                <el-input style="width: 120px;margin-right: 10px;" @input="searchDepart" v-model="Drugvalue" placeholder="输入药品名称" />
                <el-input style="width: 120px;margin-right: 10px; " @input="searchDepart" v-model="manufacturers" placeholder="输入厂家名称" />
                <el-date-picker style="width: 240px" v-model="value" type="daterange" range-separator="到"
                  start-placeholder="开始时间" end-placeholder="结束时间" size="default" @change="searchDepart" />
                <!-- <el-button style="margin: 10px" type="primary" @click="searchDepart()">搜索</el-button> -->
              </div>
              <div class="right">
                <el-button style="margin: 10px" type="primary" @click="openClass">分类管理</el-button>
                <el-button style="margin: 10px" type="danger" @click="deleteBatches">批量删除</el-button>
                <el-button style="margin: 10px" type="primary" @click="addOffice">新增药品</el-button>
              </div>
            </div>
          </template>

          <el-table v-loading="loading" ref="table" :data="pageData" style="width: 100%; margin-bottom: 20px" row-key="id"
            stripe="true" :cell-style="{ textAlign: 'center' }" :header-cell-style="{ 'text-align': 'center' }"
            max-height="68vh">
            <el-table-column type="selection" width="55" fixed="left" />
            <el-table-column prop="name" label="药品名称" width="120" show-overflow-tooltip fixed="left" />
            <el-table-column prop="class_name" label="药品分类" width="100" fixed="fixed" />
            <el-table-column prop="specifi" label="规格" width="120" />
            <el-table-column prop="heat" label="样图" width="70">
              <template #default="scope">
                <el-image :src="url + scope.row.img" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                  :preview-src-list="[url + scope.row.img]" fit="cover" preview-teleported="true"
                  style="width: 60px; height: 60px" />
              </template>
            </el-table-column>
            <el-table-column prop="number" label="库存" width="100" />
            <el-table-column prop="chase_price" label="进价" width="80" />
            <el-table-column prop="price" label="售价" width="80" />
            <el-table-column prop="manufacturer" label="生产厂家" show-overflow-tooltip width="180" />
            <el-table-column prop="date" label="生产日期" width="100" />
            <el-table-column prop="warranty" label="保质期" width="80">
              <template #default="scope">
                <div class="list_word">{{ scope.row.warranty }}个月</div>
              </template>
            </el-table-column>
            <el-table-column prop="expiration_time" label="到期时间" width="100" />
            <!-- <el-table-column prop="describe" label="药品描述" width="180" >
            <template #default="scope">
              <div class="list_word" v-html="scope.row.describe"></div>
            </template>
          </el-table-column> -->
            <el-table-column prop="status" label="是否启用" width="80">
              <template #default="scope">
                <el-switch :value="scope.row.status === 1" @click="affirmSwitch(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="进货日期" width="100" />
            <el-table-column label="操作" width="140" fixed="right">
              <!-- <template #default="scope">
              <img
                style="width: 20px; height: 20px; margin-right: 10px"
                src="../../assets/编辑.png"
                alt=""
                @click="handleEdit(scope.$index, scope.row)"
              />
              <img
                style="width: 20px; height: 20px"
                src="../../assets/删除-01.png"
                alt=""
                @click="handleDelete(scope.$index, scope.row)"
              />
            </template> -->
              <template #default="scope">
                <div style="display: flex; align-items: center; justify-content: center">
                  <el-button type="primary" plain size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                  <el-button type="danger" plain size="small"
                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div style="display: flex; justify-content: center">
            <el-pagination style="padding: 10px" v-model:current-page="currentPage" v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 30]" layout="total, sizes,->, prev, pager, next, jumper" :total="listNum"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>

        </el-card>
      </div>
      <!-- 新增/编辑页面 -->
      <el-dialog v-model="dialogFormVisible" :title="form.id <= 0 ? '新增药品信息' : '编辑药品信息'" @close="cancel()" width="50%">
        <div class="window">
          <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="100px">
            <div class="">
              <div class="box_top">
                <el-form-item label="药品名称" prop="name">
                  <el-input v-model="form.name" placeholder="输入药品名称" />
                </el-form-item>
                <el-form-item label="规格" prop="specifi" style="display: flex; align-items: center">
                  <el-input v-model="form.specifi" placeholder="输入规格如：100/ml" />
                </el-form-item>
                <el-form-item label="药品分类" prop="class_id">
                  <el-select v-model="form.class_id" clearable placeholder="请选择分类">
                    <el-option v-for="item in classList" :label="item.name" :value="item.id" :key="item.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="进价" prop="chase_price" style="display: flex; align-items: center">
                  <el-input v-model="form.chase_price" placeholder="输入进价" />
                </el-form-item>
                <el-form-item label="售价" prop="price" style="display: flex; align-items: center">
                  <el-input v-model="form.price" placeholder="输入进价" />
                </el-form-item>
                <el-form-item label="生产厂家" prop="manufacturer" style="display: flex; align-items: center">
                  <el-input v-model="form.manufacturer" placeholder="输入成产厂家" />
                </el-form-item>
                <el-form-item label="库存" prop="number" style="display: flex; align-items: center">
                  <el-input v-model="form.number" placeholder="输入库存" />
                </el-form-item>
              </div>
              <div class="box_top">
                <el-form-item label="生产日期" prop="date">
                  <el-date-picker v-model="form.date" type="date" placeholder="请选择生产日期" size="default" format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD" @change="handleChange" />
                </el-form-item>
                <el-form-item label="到期日期" prop="expiration_time">
                  <el-date-picker v-model="form.expiration_time" type="date" placeholder="生产、保质期确认自动更改" size="default"
                    readonly format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="保质期" prop="warranty">
                  <el-input-number v-model="form.warranty" :min="1" @change="handleChange" />
                  单位：月
                </el-form-item>

                <el-form-item label="药品样图" prop="img">
                  <el-upload class="avatar-uploader" :action="url + 'pc/Fileimg/file'" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :on-error="uploadError">
                    <img v-if="form.img" :src="url + form.img" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                      <Plus />
                    </el-icon>
                  </el-upload>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                  <el-switch v-model="form.status" />
                </el-form-item>
              </div>
              <div class="box_bottom">
                <el-form-item label="药品介绍" prop="describe">
                  <vue-ueditor-wrap style="width: 680px; z-index: 1" v-model="form.describe" :config="editorConfig"
                    editor-id="editor-demo-01"></vue-ueditor-wrap>
                </el-form-item>
              </div>
            </div>

            <div style="direction: rtl;">
              <el-form-item>
                <el-button type="primary" @click="affirm(ruleFormRef)" v-if="form.id <= 0">新增</el-button>
                <el-button type="primary" @click="affirm(ruleFormRef)" v-else>保存</el-button>
                <div style="width: 10px;"></div>

                <el-button @click="cancel(ruleFormRef)">取消</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-dialog>
      <!-- 分类列表 -->
      <el-dialog v-model="classVisible" title="药品分类管理">
        <div style="width: 100%; display: flex">
          <el-button style="margin: 10px" type="primary" @click="addClass">新增药品分类</el-button>
        </div>
        <el-table v-loading="loading" ref="classTable" :data="classpageData" style="width: 100%; margin-bottom: 20px"
          row-key="id" stripe="true" :cell-style="{ textAlign: 'center' }" :header-cell-style="{ 'text-align': 'center' }"
          max-height="360">
          <el-table-column prop="id" label="ID" width="70" fixed="left"> </el-table-column>
          <el-table-column prop="name" label="药品名称" fixed="left">
            <template #default="scope">
              <el-input v-if="classform.id == scope.row.id" style="width: 100px" v-model="classname" placeholder="药品名称" />
              <div v-else>{{ scope.row.name }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="150" />
          <el-table-column label="操作" width="150" fixed="right">
            <!-- <template #default="scope">
              <el-button
                size="small"
                type="primary"
                @click="classaffirms(classruleFormRef)"
                v-if="classform.id == scope.row.id"
                >确定</el-button
              >
              <img
                style="width: 20px; height: 20px; margin-right: 10px"
                src="../../assets/编辑.png"
                alt=""
                @click="classhandleEdit(scope.$index, scope.row)"
                v-else
              />
              <el-button
                size="small"
                @click="classListCancel(classruleFormRef)"
                v-if="classform.id == scope.row.id"
                >取消</el-button
              >
              <img
                style="width: 20px; height: 20px"
                src="../../assets/删除-01.png"
                alt=""
                @click="classhandleDelete(scope.$index, scope.row)"
                v-else
              />
            </template> -->
            <template #default="scope">
              <div style="display: flex; align-items: center; justify-content: center">
                <el-button size="small" type="primary" @click="classaffirms(classruleFormRef)"
                  v-if="classform.id == scope.row.id">确定</el-button>
                <el-button type="primary" plain size="small" @click="classhandleEdit(scope.$index, scope.row)"
                  v-else>编辑</el-button>
                <el-button size="small" @click="classListCancel(classruleFormRef)"
                  v-if="classform.id == scope.row.id">取消</el-button>
                <el-button type="danger" plain size="small" @click="classhandleDelete(scope.$index, scope.row)"
                  v-else>删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination style="padding: 10px" v-model:current-page="classcurrentPage" v-model:page-size="classpageSize"
          layout="total, ->, prev, pager, next, jumper" :total="classlistNum"
          @current-change="classhandleCurrentChange" />
      </el-dialog>
      <el-dialog v-model="addclassVisible" title="药品分类添加" width="40%" top="25vh">
        <el-form ref="classruleFormRef" :model="classform" :rules="classrules" label-width="120px">
          <el-form-item label="药品名称" prop="name">
            <el-input style="width: 300px" v-model="classform.name" placeholder="输入药品名称" />
          </el-form-item>
          <div style="direction: rtl;">
            <el-form-item style="width: 100%; display: flex; justify-content: flex-end">
              <el-button type="primary" @click="classaffirm(classruleFormRef)">确定</el-button>
              <div style="width: 10px;"></div>
              <el-button @click="classcancel(classruleFormRef)">取消</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
    </router-view>
  </div>
</template>

<script setup>
import { ref, watchEffect, onMounted, reactive } from 'vue';
import { addDrug, Drug, deleteDrug, addDrugs, Drugs, deleteDrugs } from '../../api/drug';
import { Plus } from '@element-plus/icons-vue';
const form = reactive({
  img: '', //图片
  name: '', //药品名称
  class_id: '', //分类id
  specifi: '', //规格
  chase_price: '', //原价
  price: '', //售价
  manufacturer: '', //生产厂家
  date: '', //生产日期
  warranty: 1, //保质期
  expiration_time: '', //到期日期
  describe: '', //药品描述
  number: '', //库存
  status: true, //状态
  id: '',
});
const classform = reactive({
  name: '', //药品分类名称
  id: '',
});
// UEditor配置
const editorConfig = reactive({
  autoHeightEnabled: false,
  initialFrameHeight: 200,
  initialFrameWidth: '100%',
  UEDITOR_HOME_URL: '/ueditor/', // 访问 UEditor 静态资源的根路径publc里面的名称
  serverUrl: '/pc/pc/Fileimg/uderto', // 服务端接⼝
  uploadUrl: '/pc/pc/Fileimg/uderto' + '/kjyl-server-doctor/doctor/file/uploadFile',
  // enableAutoSave: true, // 开启从草稿箱恢复功能需要⼿动设置固定的 editorId，否则组件会默认随机⼀个，如果页⾯刷新，下次渲染的时候 editorId 会重新随机，
});
const classname = ref('');
const dialogFormVisible = ref(false); //弹窗状态
const classVisible = ref(false); //弹窗状态
const addclassVisible = ref(false); //弹窗状态
const url = ref('https://lxt.jingyi.icu/'); //域名头
const listNum = ref(0); //列表总数
const classlistNum = ref(0); //列表总数
const currentPage = ref(1); //当前页码数
const classcurrentPage = ref(1); //当前页码数
const pageSize = ref(10); //当前每页显示数量
const classpageSize = ref(10); //当前每页显示数量
const loading = ref(true); //加载状态
const ruleFormRef = ref(); //页面表单实例
const classruleFormRef = ref();
const status = ref(true); //编辑添加页的显示隐藏状态
const table = ref(); //表格实例
const classTable = ref(); //表格实例
const DrugList = ref([]); //药品列表
const classList = ref([]); //药品列表
const manufacturers = ref(''); //搜索框内容
const Drugvalue = ref(''); //搜索框内容
const searchData = ref([]); //搜索后列表
const value = ref('');
// 图片上传
const handleAvatarSuccess = (response, uploadFile) => {
  console.log(response);
  console.log(uploadFile);
  form.img = response.data.url;
};
const uploadError = (error, uploadFile) => {
  console.log(error);
  console.log(uploadFile);
  form.img = response.data.url;
};
// 数字框改变时间
const handleChange = () => {
  let dateArray = form.date.split('-');
  console.log(dateArray);
  if (dateArray) {
    let month = (parseInt(dateArray[1]) - 1 + form.warranty) % 12;
    let year = (
      parseInt(dateArray[0]) + Math.floor((parseInt(dateArray[1]) - 1 + form.warranty) / 12)
    ).toString();
    if (parseInt(month) + 1 < 10) {
      month = '0' + (parseInt(month) + 1);
    } else {
      month = parseInt(month) + 1;
    }
    dateArray[0] = year;
    dateArray[1] = month;
    form.expiration_time = dateArray.join('-');
  } else {
    form.expiration_time = '';
  }
};
// 表单效验
const rules = reactive({
  img: [
    {
      required: true,
      message: '请上传图片',
      trigger: 'change',
    },
  ],
  name: [
    {
      required: true,
      message: '请输入药品名称',
      trigger: 'change',
    },
  ],
  class_id: [
    {
      required: true,
      message: '请选择药品分类',
      trigger: 'change',
    },
  ],
  specifi: [
    {
      required: true,
      message: '请输入规格',
      trigger: 'change',
    },
  ],
  chase_price: [
    {
      required: true,
      message: '请输入原价',
      trigger: 'change',
    },
  ],
  price: [
    {
      required: true,
      message: '请输入售价',
      trigger: 'change',
    },
  ],
  manufacturer: [
    {
      required: true,
      message: '请输入生产厂家',
      trigger: 'change',
    },
  ],
  date: [
    {
      required: true,
      message: '请选择生产日期',
      trigger: 'change',
    },
  ],
  expiration_time: [
    {
      required: true,
      message: '请选择生产日期',
      trigger: 'change',
    },
  ],
  describe: [
    {
      required: true,
      message: '请选择字体颜色',
      trigger: 'change',
    },
  ],
  number: [
    {
      required: true,
      message: '请选择字体颜色',
      trigger: 'change',
    },
  ],
});
const classrules = reactive({
  name: [
    {
      required: true,
      message: '请输入分类名称',
      trigger: 'change',
    },
  ],
});
//分页数据显示
const pageData = computed(() => {
  console.log();
  let a = [];
  for (
    let i = (currentPage.value - 1) * pageSize.value;
    i < currentPage.value * pageSize.value;
    i++
  ) {
    if (searchData.value[i]) {
      a.push(searchData.value[i]);
    }
  }
  console.log(a);
  return a;
});
//分类列表分页数据显示
const classpageData = computed(() => {
  console.log();
  let a = [];
  for (
    let i = (classcurrentPage.value - 1) * classpageSize.value;
    i < classcurrentPage.value * classpageSize.value;
    i++
  ) {
    if (classList.value[i]) {
      a.push(classList.value[i]);
    }
  }
  console.log(a);
  return a;
});
// 搜索
const searchDepart = () => {
  console.log(value.value);

  searchData.value = DrugList.value.filter(function (item) {
    let date = new Date(item.create_time).getTime();
    if (value.value) {
      let star = new Date(value.value[0]).getTime();
      let end = new Date(value.value[1]).getTime();
      if (
        date > star &&
        date < end &&
        item.name.indexOf(Drugvalue.value) > -1 &&
        item.manufacturer.indexOf(manufacturers.value) > -1
      ) {
        return item;
      }
    } else {
      if (
        item.name.indexOf(Drugvalue.value) > -1 &&
        item.manufacturer.indexOf(manufacturers.value) > -1
      ) {
        return item;
      }
    }
  });
  listNum.value = searchData.value.length;
};
// 请求列表
const requestList = async () => {
  try {
    const res = await Drug();
    console.log('药品列表', res);
    const ress = await Drugs();
    classList.value = ress.data;
    classlistNum.value = classList.value.length;
    DrugList.value = res.data.map((val, index) => {
      for (let i = 0; i < ress.data.length; i++) {
        if (ress.data[i].id == val.class_id) {
          val.class_name = ress.data[i].name;
        }
      }
      return val;
    });
    searchDepart();
    loading.value = false;
    console.log('初次列表', searchData.value);
  } catch (error) {
    console.error(error);
  }
};
requestList();
// 每页显示数量改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  console.log(`${val} items per page`);
};
// 页码数改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  console.log(`current page: ${val}`);
};
// 分类页码数改变
const classhandleCurrentChange = (val) => {
  classcurrentPage.value = val;
  console.log(`current page: ${val}`);
};
// 编辑
const handleEdit = (index, row) => {
  dialogFormVisible.value = true;
  form.id = row.id;
  form.name = row.name;
  form.img = row.img;
  form.class_id = row.class_id;
  form.specifi = row.specifi;
  form.chase_price = row.chase_price;
  form.price = row.price;
  form.manufacturer = row.manufacturer;
  form.date = row.date;
  form.warranty = row.warranty;
  form.expiration_time = row.expiration_time;
  form.describe = row.describe;
  form.number = row.number;
  form.status = row.status == 1 ? true : false;
  console.log(form);
  console.log(index, row);
};
// 删除
const handleDelete = (index, row) => {
  console.log(index, row);
  ElMessageBox.confirm('是否确认删除?', '删除药品', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then((res) => {
      console.log(res);

      deleteDrug({
        id: row.id,
      }).then((result) => {
        console.log(result);
        if (result.code == 0) {
          ElMessage({
            type: 'danger',
            message: result.msg,
          });
        } else if (result.code == 1) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          });
          requestList();
        }
      });
    })
    .catch((res) => {
      console.log(res);
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
};

const deleteBatches = () => {
  let arr = table.value.getSelectionRows();
  if (arr.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择需要删除的数据',
    });
    return;
  }

  ElMessageBox.confirm('是否确认删除?', '删除药品', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then((res) => {
      console.log(res);
      let arr = table.value.getSelectionRows();
      let arrs = [];
      console.log(arr);
      // 构造一个 Promise 数组，每个 Promise 表示一条记录的删除操作
      const promises = arr.map((element) => {
        return deleteDrug({ id: element.id });
      });
      // 使用 Promise.all() 处理 Promise 数组，一旦其中有一个Promise被拒绝（即删除失败），就会执行catch()方法，
      // 否则，如果所有的Promise都得到了解决（即删除成功），就会执行then()方法。
      Promise.all(promises)
        .then((results) => {
          console.log(results);
          results.forEach((result) => {
            if (result.code == 0) {
              ElMessage({
                type: 'danger',
                message: result.msg,
              });
            } else if (result.code == 1) {
              arrs.push(result.data);
            }
          });
          if (arrs.length == arr.length) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            });
          } else {
            ElMessage({
              type: 'warning',
              message: '删除失败，请重试',
            });
          }
          requestList();
        })
        .catch((error) => {
          console.log(error);
          ElMessage({
            type: 'warning',
            message: '删除失败，请重试',
          });
        });
    })
    .catch((res) => {
      console.log(res);
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
};
// 批量删除
// const deleteBatches = () => {
//   ElMessageBox.confirm('是否确认删除?', '删除药品', {
//     confirmButtonText: '确认',
//     cancelButtonText: '取消',
//     type: 'warning',
//   })
//     .then((res) => {

//     })
//     .catch((res) => {
//       console.log(res);
//       ElMessage({
//         type: 'info',
//         message: '取消删除',
//       });
//     });
// };

// 新增
const addOffice = () => {
  form.id = '';
  clearForm();
  dialogFormVisible.value = true;
  ruleFormRef.value.clearValidate();
};
// 清空表单
const clearForm = () => {
  form.img = '';
  form.name = '';
  form.class_id = '';
  form.specifi = '';
  form.chase_price = '';
  form.price = '';
  form.manufacturer = '';
  form.date = '';
  form.warranty = 1;
  form.expiration_time = '';
  form.describe = '';
  form.number = '';
  form.status = true;
};
// 取消
const cancel = (formEl) => {
  clearForm();
  dialogFormVisible.value = false;
  formEl.clearValidate();
};
// 确认新增/编辑
const affirm = async (formEl) => {
  console.log(form);
  if (form.status) {
    form.status = 1;
  } else {
    form.status = 2;
  }
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addDrug(form).then((res) => {
        console.log(res);
        if (form.id) {
          ElMessage({
            type: 'success',
            message: '编辑成功',
          });
        } else {
          ElMessage({
            type: 'success',
            message: '添加成功',
          });
        }
        dialogFormVisible.value = false;
        clearForm();
        requestList();
      });
      console.log('submit!');
    } else {
      console.log('error submit!', fields);
    }
  });
};
// 列表状态编辑
const affirmSwitch = (data) => {
  console.log(data);
  if (data.status == 1) {
    data.status = 2;
  } else {
    data.status = 1;
  }

  addDrug(data).then((res) => {
    console.log(res);
    if (res.code == 0) {
      ElMessage({
        type: 'danger',
        message: '状态更改失败',
      });
    } else {
      ElMessage({
        type: 'success',
        message: '状态更改成功',
      });
    }

    requestList();
  });
};
// 打开分类列表
const openClass = () => {
  classVisible.value = true;
};
// 打开添加分类
const addClass = () => {
  addclassVisible.value = true;
  classruleFormRef.value.clearValidate();
};
// 确认新增
const classaffirm = async (formEl) => {
  if (classform.id) {
    if (classname.value) {
      classform.name = classname.value;
    } else {
      ElMessage({
        type: 'warning',
        message: '请输入药品名称',
      });
      return;
    }
  }
  console.log(classform);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addDrugs(classform).then((res) => {
        console.log(res);
        if (classform.id) {
          ElMessage({
            type: 'success',
            message: '编辑成功',
          });
        } else {
          ElMessage({
            type: 'success',
            message: '添加成功',
          });
        }
        addclassVisible.value = false;
        classform.name = '';
        classruleFormRef.value.clearValidate();
        requestList();
      });
      console.log('submit!');
    } else {
      console.log('error submit!', fields);
    }
  });
};
// 确认编辑
const classaffirms = async (formEl) => {
  if (classname.value) {
    classform.name = classname.value;
  } else {
    ElMessage({
      type: 'warning',
      message: '请输入药品名称',
    });
    return;
  }
  console.log(classform);
  addDrugs(classform).then((res) => {
    console.log(res);
    ElMessage({
      type: 'success',
      message: '编辑成功',
    });
    addclassVisible.value = false;
    classform.name = '';
    classform.id = '';
    requestList();
  });
};
// 取消
const classcancel = () => {
  classform.name = '';
  addclassVisible.value = false;
  classruleFormRef.value.clearValidate();
};
// 列表取消
const classListCancel = () => {
  classform.id = '';
};
// 编辑
const classhandleEdit = (index, row) => {
  classform.id = row.id;
  classname.value = row.name;
  console.log(form);
  console.log(index, row);
};
// 删除
const classhandleDelete = (index, row) => {
  console.log(index, row);
  ElMessageBox.confirm('是否确认删除?', '删除药品', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then((res) => {
      console.log(res);

      deleteDrugs({
        id: row.id,
      }).then((result) => {
        console.log(result);
        if (result.code == 0) {
          ElMessage({
            type: 'danger',
            message: result.msg,
          });
        } else if (result.code == 1) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          });
          requestList();
        }
      });
    })
    .catch((res) => {
      console.log(res);
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
};
</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  background-color: rgb(255, 255, 255);
  overflow-y: scroll;
}

.left {
  max-width: 650px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.right {
  max-width: 400px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
}

.header {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.head_word {
  width: 100%;
  padding: 10px 20px;
  border-bottom: 1px solid #e5e5e5;
  margin-bottom: 20px;
  color: #427eff;
}

.window {
  width: 100%;
  // overflow-x: scroll;
  padding: 10px;
  background-color: white;
}

.hint {
  margin-left: 10px;
  color: #a6a6a6;
  font-size: 14px;
}

.head_img {
  width: 40px;
  height: 40px;
  border-radius: 40px;
}

.lable {
  width: 100%;
  line-height: 1;
  border-radius: 50px;
  padding: 10px;
}

.list_word {
  width: 100%;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.inpuut_box {
  width: 800px;
  display: flex;
  flex-wrap: wrap;
}

.box_bottom {
  width: 800px;
}

//上传
.avatar-uploader {
  border: 1px dashed var(--el-border-color) !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  display: flex;
  align-items: center;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

//上传
.form_word {
  margin-right: 20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.list_word {
  width: 100%;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
